package com.emm.yixun.website.controller.marketing;
//框架包
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.emm.yixun.anotations.AvoidDuplicateSubmission;
import com.emm.yixun.common.model.Project;
//变化的引用
import com.emm.yixun.common.model.SalesTarget;
import com.emm.yixun.common.model.SalesTargetPmo;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.SalesTargetDto;
import com.emm.yixun.common.model.dto.SalesTargetPmoDto;
//common
import com.emm.yixun.common.response.Response;
//common
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.estate.service.ProjectServiceFacade;
import com.emm.yixun.marketing.service.SalesTargetServiceFacade;
//website
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.utils.TokenProcessor;
@Controller
@RequestMapping("/marketing/salesTarget/")
public class SalesTargetController extends BaseController<SalesTarget>{
	
	@Autowired
	private SalesTargetServiceFacade salesTargetServiceFacade;
	@Autowired
	private ProjectServiceFacade projectServiceFacade;
	
	@RequestMapping(value="index")

	public String index(ModelMap map,HttpServletRequest request){
		if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){
			//查询菜单按钮权限
			map.put("permitBtn", getPermissionBtnArray());		
			map.put("menu", request.getParameter("menu"));
			return "/marketing/salesTarget/list";
		}
		return Const.NO_AUTHORIZED_URL;
	}
	@RequestMapping(value = "addView")
	@AvoidDuplicateSubmission(needSaveToken = true)
	public ModelAndView addView(Long projectId,Long type,String salesYear,HttpServletRequest request){
		ModelAndView mv = new ModelAndView("/marketing/salesTarget/add");
		Response<Project> project =  projectServiceFacade.findById(projectId);
		SalesTargetDto sales = new SalesTargetDto();
		sales.setProjectId(projectId);
		sales.setDelFlag("0");
		sales.setQuotaType(type.toString());
		sales.setSalesYear(salesYear);
		mv.addObject("salesYear", salesYear);
		if(project.isSuccess()){
			mv.addObject("projectName", project.getEntity().getProjectName());
			mv.addObject("projectId", projectId);
			mv.addObject("type", type);
			
		}
		mv.addObject("permitBtn", getPermissionBtnArray());	
		mv.addObject("menu", request.getParameter("menu"));
		return mv;
	}
	
	//新增返回实体对象
	@RequestMapping(value="add")
	@ResponseBody
	@AvoidDuplicateSubmission(needRemoveToken = true)
    public AjaxRes  add(SalesTargetDto dto, HttpServletRequest request){
    	AjaxRes ar=getAjaxRes();
    	//操作失败时,重新刷新提交Token
    	String newToken = TokenProcessor.getInstance().generateToken(request);
    	request.getSession(false).setAttribute("token", newToken);
    	/*
    	 *1.判断权限 
    	 *2.调用新增接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"marketing:salesTarget:add"))){
        	try { 
        		List<SalesTargetDto> list = convertList(dto.getJson());
				Response<SalesTargetDto> response=salesTargetServiceFacade.save(dto,list,ShiroUtil.getCurrentUser());
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.SAVE_SUCCEED);
				}else{
					ar.setFailMsg(response.getResultMessage());
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
    	}
        //操作失败,重置防重复提交Token
        if(Const.FAIL == ar.getRes()){
        	ar.setObj(newToken);
        }
    	return ar;
    }
	//查看
	@RequestMapping(value="view", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  view(Long id){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用查看接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"marketing:salesTarget:view"))){
        	try {
				Response<SalesTarget> response=salesTargetServiceFacade.findById(id);
				if(response.isSuccess()){
					ar.setSucceed(response.getEntity());
				}else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
    	}
    	return ar;
    }
	
	//修改
	@RequestMapping(value="edit", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  edit(SalesTargetDto dto){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用修改接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"marketing:salesTarget:edit"))){
        	try {
        		Response<Integer> response=salesTargetServiceFacade.updateByPrimaryKey(dto, true);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.UPDATE_SUCCEED);
				}else{
					ar.setFailMsg(Const.UPDATE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
    	}
    	return ar;
    }
	
	//删除
	@RequestMapping(value="delete")
	@ResponseBody
    public AjaxRes  delete(SalesTargetDto dto){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用查看接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"marketing:salesTarget:delete"))){
        	try {
        		Response<Boolean> response=salesTargetServiceFacade.clearSalesTarget(dto);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.DEL_SUCCEED);
				}else {
					ar.setFailMsg(Const.DEL_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DEL_FAIL);
			}
    	}
    	return ar;
    }
	
	//分页查询
	@RequestMapping(value="list")
	@ResponseBody
    public List<SalesTargetDto>  list(SalesTargetDto dto){
    	/*
    	 *1.判断权限 
    	 *2.调用分页查询接口
    	 *3.返回信息
    	*/
        if(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"marketing:salesTarget:list")){
        	try{
        		User user = ShiroUtil.getCurrentUser();
        		dto.setPermissionUserId(user.getId());
        		
        		//项目数据权限资源缓存
        		String resourcesCode = dto.getResourcesCode();
        		if(StringUtils.isBlank(resourcesCode)){
        			resourcesCode = ShiroUtil.getDataPermissionResources(dto.getResourcesName());
        			dto.setResourcesCode(resourcesCode);
        		}
        		ShiroUtil.setDataPermissionResources(dto.getResourcesName(), resourcesCode);
        		dto.setMerchantId(user.getMerchantId());
        		List<SalesTargetDto>  list =salesTargetServiceFacade.findSumList(dto);
        		return  list;
			} catch (Exception e) {
				logger.error(e.toString(),e);
			}
    	}
    	return new ArrayList<SalesTargetDto>();
    }
	/**
	* 方法描述 : 销售组指标列表
	* 创建者：ThinkPad 
	* 项目名称： emm-website
	* 类名： SalesTargetController.java
	* 版本： v1.0
	* 创建时间： 2016年6月29日 下午3:13:51
	* @param projectId
	* @param type
	* @return List<SalesTargetDto>
	 */
	@RequestMapping(value = "findAddList")
	public @ResponseBody List<SalesTargetDto> findAddList(Long projectId,Long type,String salesYear){
		List<SalesTargetDto> list = salesTargetServiceFacade.findAddList(projectId,type,salesYear);
		return list;
	}
	/**
	* 方法描述 : JSON字符串转换成LIST
	* 创建者：ThinkPad 
	* 项目名称： emm-website
	* 类名： SalesTargetController.java
	* 版本： v1.0
	* 创建时间： 2016年6月30日 上午11:34:12
	* @param json
	* @return List<SalesTarget>
	 */
	public List<SalesTargetDto> convertList(String json){
		JSONArray jsonarray = JSONArray.fromObject(json);
		@SuppressWarnings("unchecked")
		List<Object> objectList = (List<Object>) JSONArray.toCollection(jsonarray, Object.class);
		List<SalesTargetDto> array = new ArrayList<SalesTargetDto>();
		for (int i = 0; i < objectList.size(); i++) {
			JSONObject jsonObject=JSONObject.fromObject(objectList.get(i));
			SalesTargetDto obj = (SalesTargetDto)JSONObject.toBean(jsonObject,SalesTargetDto.class);
			array.add(obj);
		}
		return array;
	}
	/**
	* 方法描述 : 各项指标累计
	* 创建者：ThinkPad 
	* 项目名称： emm-website
	* 类名： SalesTargetController.java
	* 版本： v1.0
	* 创建时间： 2017年3月22日 上午11:04:39
	* @param dto
	* @return List<SalesTargetDto>
	 */
	@RequestMapping(value = "findCumulativeGrid")
	public @ResponseBody List<SalesTargetPmo> findCumulativeGrid(SalesTargetPmoDto dto){
		List<SalesTargetPmo> array = new ArrayList<SalesTargetPmo>();
		ResponseList<SalesTargetPmo> responseList = salesTargetServiceFacade.findCumulativeGrid(dto);
		if(responseList.getEntity()!=null){
			array=responseList.getEntity();
		}
		return array;
	}
}
